package com.cn.studey.config;

import com.cn.studey.entity.mqentity.MqMessage;
import com.cn.studey.listeningmessage.rocketmqmessage.DealMessage;
import com.cn.studey.listeningmessage.rocketmqmessage.DelMessageFactory;
import com.cn.studey.utils.ByteObjectUtils;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @author mjy(配置RocketMq监听)
 * @date 2021/12/20
 * @description
 */
@Configuration
public class RocketMqConsumerConfiguration implements ApplicationRunner {


    Logger log = LoggerFactory.getLogger(RocketMqConsumerConfiguration.class);

    @Autowired
    private RocketMqConfig rocketMqConfig;

    @Bean
    public DefaultMQPushConsumer createMqConsumer() throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(rocketMqConfig.getWebGroup());
        consumer.setNamesrvAddr(rocketMqConfig.getNameServer());
        consumer.subscribe(rocketMqConfig.getWebTopic(),rocketMqConfig.getWebTag());
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt msg : list) {
                    MqMessage mqMessage = transformMsg(msg);
                    DealMessage dealMessage = DelMessageFactory.createDealMessage(mqMessage);
                    dealMessage.dealMessage(mqMessage);
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        consumer.start();
       return consumer;
    }


    @Override
    public void run(ApplicationArguments args) throws Exception {
        this.createMqConsumer();
    }


    /**
     * 消息对象转化
     *
     * @param msg
     * @return
     */
    private MqMessage transformMsg(MessageExt msg) {
        MqMessage mqMessage = (MqMessage) ByteObjectUtils.toObject(msg.getBody());
        return mqMessage;
    }


}
